package com.ruyuan.seckilling.render.async.listener;

import com.ruyuan.seckilling.render.async.BaseRenderPageListener;
import com.ruyuan.seckilling.render.async.PageRenderContext;
import com.ruyuan.seckilling.render.async.event.Event02DownloadTemplateFile;
import com.ruyuan.seckilling.render.service.FileService;
import com.ruyuan.starter.async.anno.Channel;
import com.ruyuan.starter.async.event.BaseEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

import static com.ruyuan.seckilling.common.ChannelKey.CHANNEL_02_DOWNLOAD_TEMPLATE_FILE;
import static com.ruyuan.seckilling.common.ChannelKey.CHANNEL_03_AGGR_DATA;
import static com.ruyuan.seckilling.render.async.PageRenderEventHolder.EVENT_03;

/**
 * @author zhonghuashishan
 */
@Slf4j
@Component
@Channel(CHANNEL_02_DOWNLOAD_TEMPLATE_FILE)
public class Event02Listener extends BaseRenderPageListener<Event02DownloadTemplateFile> {

    @Autowired
    private FileService fileService;

    @Override
    public boolean accept(BaseEvent event) {
        return event instanceof Event02DownloadTemplateFile;
    }

    /**
     * 2、下载页面模板文件
     */
    @Override
    protected void doThisStep(Event02DownloadTemplateFile event, PageRenderContext context) {

        Runnable task = () -> {
            String templateContent = fileService.download(context.getPageConfig().getTemplateUrl());
            if (Objects.isNull(templateContent)) {
                context.getPageLog().setSuccess(false);
                context.getPageLog().setInfo("模板文件不存在");
                context.setShouldSkip(true);
                return;
            }
            context.setTemplateContent(templateContent);
            bossEventBus.publish(CHANNEL_03_AGGR_DATA, EVENT_03, context);
            log.info("第2步，下载模板文件");
        };

        executorService.execute(CHANNEL_02_DOWNLOAD_TEMPLATE_FILE, task);
    }
}
